﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 创建者：王明亮
 * 创建时间：2023/9/25 10:32:29
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using JwtApiDemo.Comm;
using JwtApiDemo.Helper;
using JwtApiDemo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using static JwtApiDemo.Helper.JwtHelper;

namespace JwtApiDemo.Filters
{
    /// <summary>
    /// 授权认证
    /// </summary>
    public class AuthorizeFilter : Attribute, IActionFilter
    {

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var controller = context.RouteData.Values["controller"].ToString();
            //var action = context.RouteData.Values["action"].ToString();
            if (controller == "User" || controller == "Jwt")
            {
                //登录接口不验证
            }
            else
            {
                var authHeader = context.HttpContext.Request.Headers["Authorization"];
                if (string.IsNullOrWhiteSpace(authHeader))
                {
                    //此接口必须携带token访问！
                    context.Result = new JsonResult(new OperationResult(OperationResultType.Error, "此接口必须携带token访问，请登录携带Token访问"));
                }
                else //字段值不为空
                {
                    authHeader = authHeader.ToString().Replace("Bearer", "").Trim();//去掉Bearer字串
                    if (authHeader == "")
                    {
                        context.Result = new JsonResult(new OperationResult(OperationResultType.Error, "token验证失败：您没有权限调用此接口，请登录重新获取Token"));
                    }
                    else
                    {
                        LoginUserInfo LoginInfo = JwtHelper.GetJwtDecode(authHeader);
                        if (LoginInfo == null)
                        {
                            context.Result = new JsonResult(new OperationResult(OperationResultType.Error, "Token验证失败"));
                        }
                        string UserName = LoginInfo.username;
                        string PassWord = LoginInfo.pwd;
                        string ExpireTimeStamp = LoginInfo.exp;
                        //var cacheToken = Cache.Get(UserName);
                        if (isTokenExpire(ExpireTimeStamp)) //这里应该验证有效期
                        {
                            context.Result = new JsonResult(new OperationResult(OperationResultType.Error, "token验证失败：您没有权限调用此接口，请登录重新获取Token"));
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 时间戳字符串
        /// </summary>
        /// <param name="timestampstr"></param>
        /// <returns></returns>
        private bool isTokenExpire(string timestampstr)
        {
            try
            {
                double timestamp = double.Parse(timestampstr);
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                var expireTime = startTime.AddSeconds(timestamp);
                if (expireTime > DateTime.Now)
                {
                    return false;//未过期
                }
                else
                {
                    return true;//已过期
                }
            }
            catch (Exception ex)
            {
                return true;
            }
        }

    }
}
